<!-- src/views/Login.vue -->
<template>
  <div id="login-page">
    <div class="login-container">
      <h2 class="login-title">
        <i class="fas fa-university"></i> 校园活动管理系统
      </h2>
      <form @submit.prevent="handleLogin" id="login-form">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            v-model="username"
            type="text"
            id="username"
            placeholder="请输入用户名"
            required
          />
        </div>
        <div class="form-group">
          <label for="password">密码</label>
          <input
            v-model="password"
            type="password"
            id="password"
            placeholder="请输入密码"
            required
          />
        </div>
        <div class="form-group">
          <label for="role">角色</label>
          <select v-model="role" id="role" required>
            <option value="">请选择角色</option>
            <option value="applicant">活动申请人</option>
            <option value="department_head">部门负责人</option>
            <option value="advisor">指导老师</option>
            <option value="equipment_manager">物资管理员</option>
          </select>
        </div>
        <button type="submit" class="btn" :disabled="loading">
          {{ loading ? '登录中...' : '登录' }}
        </button>
      </form>
      <p>
        没有账号？<a href="#" @click.prevent="goToRegister">立即注册</a>
      </p>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

const username = ref('')
const password = ref('')
const role = ref('')
const loading = ref(false)
const router = useRouter()

const handleLogin = async () => {
  if (!username.value || !password.value || !role.value) {
    alert('请填写完整信息')
    return
  }

  loading.value = true
  try {
    const response = await axios.post('http://localhost:8080/api/v1/user/login', {
      username: username.value,
      password: password.value,
      role: role.value
    })

    const resp = response.data // Response<LoginResult>

    // ✅ 重点修复：后端 SUCCESS.code 是 "0000"，不是 "200"！
    if (String(resp.code) === '0000') {
      if (resp.data) {
        localStorage.setItem('token', resp.data.token || '')
        localStorage.setItem('role', resp.data.role || '')
      }

      const dataToShow = resp.data || {}
      const displayText = JSON.stringify(dataToShow, null, 2)
      alert(`✅ 登录成功！\n\n返回的 data 内容：\n${displayText}`)

      // 可选：登录成功后跳转首页
      router.push('/') // 或根据角色跳转不同页面
    } else {
      // 业务失败（如密码错误、用户不存在等）
      alert(`❌ 登录失败\nCode: ${resp.code}\nInfo: ${resp.info || '未知错误'}`)
    }
  } catch (error) {
    console.error('登录请求失败:', error)
    if (error.response) {
      const errMsg = error.response.data?.info || '服务器处理失败'
      alert('登录失败：' + errMsg)
    } else if (error.request) {
      alert('无法连接到后端服务，请确保 Spring Boot 应用已启动（端口 8080）')
    } else {
      alert('请求出错：' + error.message)
    }
  } finally {
    loading.value = false
  }
}

const goToRegister = () => {
  router.push('/register')
}
</script>

<style scoped>
/* 样式保持不变 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
}
#login-page {
  background-color: #f5f7fa;
  color: #333;
  line-height: 1.6;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-container {
  max-width: 400px;
  width: 100%;
  padding: 30px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}
.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #1e88e5;
}
.form-group {
  margin-bottom: 20px;
}
label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #555;
}
input,
select,
textarea {
  width: 100%;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}
.btn {
  width: 100%;
  display: inline-block;
  background: #1e88e5;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  text-decoration: none;
  transition: background 0.3s;
}
.btn:hover {
  background: #1565c0;
}
.btn:disabled {
  background: #90caf9;
  cursor: not-allowed;
}
p {
  text-align: center;
  margin-top: 20px;
}
p a {
  color: #1e88e5;
  text-decoration: none;
}
p a:hover {
  text-decoration: underline;
}
</style>
